<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { importEmployees } from '@/api/employess'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  methods: {
    async handleSuccess({ header, results }) {
      console.log(header, results)
      this.tableData = results
      this.tableHeader = header
      const res = this.transExcel(results)
      try {
        await importEmployees(res)
        this.$message.success('导入成功')
        this.$router.back()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 转换格式
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj)
        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          // 判断
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
    }
  }
}
</script>
